import React, {Component} from 'react';
import {Toast} from 'antd-mobile';
import './CityList.scss'
import NavHeader from "../../components/NavHeader/NavHeader";
import {require} from "../../netWork";
import {getCurrentCity} from "../../utiles";
//长列表
import {List, AutoSizer} from 'react-virtualized'
//根据首字母分类城市
const fromCityData = (data) => {
    let cityList = {};
    let cityIndex = [];
    //遍历数组
    data.forEach(item => {
        const frist = item.short.substr(0, 1)
        //根据首字母分类
        if (cityList[frist]) {
            cityList[frist].push(item)
        } else {
            cityList[frist] = [item]
        }
    });

    cityIndex = Object.keys(cityList).sort();
    return {
        cityList,
        cityIndex,
    }

};

//将对应的hot转为热门城市
const updataIndex = (letter) => {
    switch (letter) {
        case '#':
            return '当前城市'
        case 'hot':
            return '热门城市'
        default :
            return letter.toUpperCase()
    }
}
//热门城市
const HOST_CITY = ['北京','上海','广州','深圳']
//城市选择列表
class CityList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cityList: {},
            cityIndex: [],
            cityActive: 0
        };
        this.cityListComoonent = React.createRef()
    }


    componentDidMount() {
        //获取城市列表
        require({
            url:'/area/city',
            data:{level:1}
        }).then(res => {
            var {cityList, cityIndex} = fromCityData(res.body);
            // console.log(cityIndex, cityList);
            return {cityList, cityIndex}
        }).then(list => {
                //输出cityList,cityIndex
                // console.log(list);
                //获取热门城市
                require({
                    url: '/area/hot'
                }).then(hot => {
                    // console.log(hot);
                    //往列表中添加热门城市
                    list.cityList['hot'] = hot.body;
                    list.cityIndex.unshift('hot');

                    //获取当前城市
                    getCurrentCity().then(res => {
                        list.cityList['#'] = [res]
                        list.cityIndex.unshift('#')
                        this.setState({cityList: list.cityList, cityIndex: list.cityIndex})
                        // console.log(list);
                    });
                })
            }
        ).catch(onerror => {
            console.log(onerror);
        })

    };

    //每个列表项的高度
    getRowHeight = ({index}) => {
        const {cityList, cityIndex} = this.state
        return (36 + cityList[cityIndex[index]].length * 35)
    };

    //点击城市 切换城市
    changeCity = (city) =>{
        const {label,value} = city;
        if(HOST_CITY.indexOf(label) > -1){
            localStorage.setItem('hkzf', JSON.stringify({label,value}));
            this.props.history.go(-1)
        }else {

            Toast.info('暂无房源数据', 1,null,true);
        }
    };

    //长列表
    rowRenderer = ({
                       key, // Unique key within array of rows
                       index, // Index of row within collection
                       isScrolling, // The List is currently being scrolled是否滚动中
                       isVisible, // This row is visible within the List (eg it is not an overscanned row)当前项在list中可见
                       style, // Style object to be applied to row (to position it)
                   }) => {
        const {cityIndex, cityList} = this.state;
        const letter = cityIndex[index]
        // console.log(cityList[letter]);
        return (
            <div key={key} style={style} className='autosizer'>
                <div className='title'>{updataIndex(letter)}</div>
                {
                    cityList[letter].map(item => {
                        return <div className='name' key={item.value} onClick={() =>{this.changeCity(item)}}> {item.label} </div>
                    })}

            </div>
        );
    }
    //右侧索引
    getRightIndex = () => {
        const {cityIndex, cityActive} = this.state;
        return cityIndex.map((item, index) => {
            return <li className='right_index_item' key={index} onClick={() => {
                this.cityListComoonent.current.scrollToRow(index)
            }}>
                <span
                    className={cityActive === index ? 'right_index_active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
            </li>
        })
    };

    //获取高度
    onRowsRendered = ({startIndex}) => {
        if (this.state.cityActive !== startIndex) {
            this.setState({
                cityActive: startIndex
            })
        }
    };

    render() {
        return (
            <div className='cityList'>
                <div className='navheader-header'>
                    <NavHeader >城市列表</NavHeader>
                </div>

                {/*城市列表*/}
                <AutoSizer>
                    {
                        ({width, height}) =>
                            <List
                                ref={this.cityListComoonent}
                                width={width}
                                height={height}
                                rowCount={this.state.cityIndex.length}
                                rowHeight={this.getRowHeight}
                                rowRenderer={this.rowRenderer}
                                onRowsRendered={this.onRowsRendered}
                                scrollToAlignment={'start'}
                            />

                    }
                </AutoSizer>
                {/*右侧索引*/}
                <ul className='right_index'>
                    {this.getRightIndex()}
                </ul>

            </div>
        );
    }
}

export default CityList;
